package com.taldh.mutlithread.deadlock;

import org.springframework.scheduling.concurrent.ThreadPoolExecutorFactoryBean;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * date 2020/7/6
 *
 * @author 袁小黑
 * @version 1.0.0
 **/

public class DeadLockDemo {

    private static Object lockA = new Object();
    private static Object lockB = new Object();

    private static class LockAThenB implements Runnable {
        @Override
        public void run() {
            synchronized (lockA) {
                System.out.println(Thread.currentThread().getName()+ "获得 lockA 锁");
                synchronized (lockB) {
                    System.out.println(Thread.currentThread().getName() + "获得 lockB 锁");
                }
            }
        }
    }

    private static class LockBThenA implements Runnable {
        @Override
        public void run() {
            synchronized (lockB) {
                System.out.println(Thread.currentThread().getName()+ "获得 lockA 锁");
                synchronized (lockA) {
                    System.out.println(Thread.currentThread().getName() + "获得 lockB 锁");
                }
            }
        }
    }

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        int count = 10;
        while (count-- > 0) {
            executorService.execute(new LockAThenB());
            executorService.execute(new LockBThenA());
        }
    }
}
